package com.xuecheng.content.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class CourseBaseServiceImpl implements CourseBaseService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //进行分页查询你
        //1.条件查询，查询条件
        //2.拼装查询条件,开始
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //进行模糊查询
        lambdaQueryWrapper.like(StringUtils.isNotBlank(queryCourseParamsDto.getCourseName()),CourseBase::getName ,queryCourseParamsDto.getCourseName());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        //开始分页，当前页码和每页记录数

        Page<CourseBase> page = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page,lambdaQueryWrapper);
        //分页查询结果格式化
        //分页列表
        List<CourseBase> courseBaseList = pageResult.getRecords();
        //分页总数
        long count = pageResult.getTotal();
        //分页封装
        return new PageResult<>(courseBaseList,count,pageParams.getPageNo(),pageParams.getPageSize());
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId,AddCourseDto addCourseDto) {
        //参数合法校验
        if(addCourseDto.getName() == null){
            XueChengPlusException.cast("课程名称不能为空");
        }
        if(addCourseDto.getPrice() == null){
            XueChengPlusException.cast("课程价格不能为空");
        }
        if(addCourseDto.getCharge() == null){
            XueChengPlusException.cast("收费规则不能为空");
        }
        if(addCourseDto.getGrade() == null){
            XueChengPlusException.cast("课程等级不能为空");
        }
        if(addCourseDto.getSt() == null){
            XueChengPlusException.cast("课程分类不能为空");
        }
        if(addCourseDto.getUsers() == null){
            XueChengPlusException.cast("适用人群不能为空");
        }

        //像课程基本表写入数据，使用BeanUtil进行属性拷贝
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //默认审核状态为未审核
        courseBase.setAuditStatus("202002");
        //默认发布状态为未发布
        courseBase.setStatus("203001");
        int insert = courseBaseMapper.insert(courseBase);
        if(insert <= 0){
            throw new RuntimeException("添加课程失败");
        }

        //向课程营销标插入数据
        CourseMarket courseMarket = new CourseMarket();
        //属性拷贝
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        //保证课程id 和营销id相同
        Long id = courseBase.getId();
        courseMarket.setId(id);
        //创建一个私有方法实现当数据库中有这条数据就跟新，没有就插入
        saveCourseMarket(courseMarket);
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(id);
        return  courseBaseInfo;

    }

    //查询课程详细信息
        public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        //查询课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return  null;
        }
        //查询课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //组装信息
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //TODO:把课程的分类名称设置到课程详细信息中
        //获得课程的分类id
        String mt = courseBaseInfoDto.getMt();
        String st = courseBaseInfoDto.getSt();
        CourseCategory courseCategory = courseCategoryMapper.selectById(st);
        CourseCategory ParentCourseCategory = courseCategoryMapper.selectById(mt);
        courseBaseInfoDto.setStName(courseCategory.getName());
        courseBaseInfoDto.setMtName(ParentCourseCategory.getName());
        return courseBaseInfoDto;
    }

    /**
     * 修改课程信息
     * @param companyId
     * @param editCourseDto
     * @return
     */
    @Override
    public CourseBaseInfoDto updateCourseBaseInfoDto(Long companyId,EditCourseDto editCourseDto) {
       //合法性校验
        //本机构只能修改本机构的课程信息
        CourseBase courseBase = courseBaseMapper.selectById(editCourseDto.getId());

        if(courseBase == null){
            XueChengPlusException.cast("课程为空");
        }
        if(!courseBase.getCompanyId().equals(companyId)){
        XueChengPlusException.cast("该课程不是本机构的课程，不能修改");
        }
        //封装数据,更新基本信息
        BeanUtils.copyProperties(editCourseDto,courseBase);
        //更新营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(editCourseDto.getId());
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        //把修改人和修改时间填充进去
        courseBase.setChangeDate(LocalDateTime.now());
        //更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        int i1 = courseMarketMapper.updateById(courseMarket);
        if(i <= 0 || i1 <= 0){
            XueChengPlusException.cast("修改课程失败");
        }
        //查询更新后的课程信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(editCourseDto.getId());
        return courseBaseInfo;
    }


    //创建一个私有方法实现当数据库中有这条数据就跟新，没有就插入
    private int saveCourseMarket(CourseMarket courseMarket){
        //参数合法校验
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new RuntimeException("收费规则为空");
        }
        if(charge.equals("201001")){
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0){
                //throw new RuntimeException("课程价格必须大于0且不为空");
                XueChengPlusException.cast("课程价格必须大于0且不为空");
            }
        }
        //查询数据库中是否有数据，有则更新，无则添加
        Long id = courseMarket.getId();
        CourseMarket courseMarket1 = courseMarketMapper.selectById(id);
        if(courseMarket1 == null){
            int insert = courseMarketMapper.insert(courseMarket);
            if(insert <= 0){

                XueChengPlusException.cast("课程营销添加失败");
            }
            return insert;
        }else{
            //跟新数据库内容
            BeanUtils.copyProperties(courseMarket,courseMarket1);
            courseMarket1.setId(courseMarket.getId());
            int i = courseMarketMapper.updateById(courseMarket1);
            if(i <= 0){
                XueChengPlusException.cast("课程营销更新失败");
            }
            return i;
        }
    }
}
